import {
	useState,
	useRef,
	useCallback,
	type FC,
	forwardRef,
	useImperativeHandle,
} from "react";
import LazyLoadImage from "./LazyLoadImage";
import { Swiper, type SwiperRef } from "antd-mobile";
import type { GreatJoySwiperProps, SwiperItemType } from "./type";

/**
 * 懒加载轮播组件
 * @param items 轮播项列表
 * @param height 轮播高度
 * @param autoplay 是否自动播放
 * @param interval 自动播放间隔
 * @param loop 是否循环播放
 * @param lazyLoadThreshold 懒加载阈值 单位px
 * @param placeholder 占位图
 * @param onSlideChange 轮播切换回调
 * @param renderCustomItem 自定义轮播项渲染函数
 * @param className 样式类名
 */

const GreatJoySwiper: FC<GreatJoySwiperProps> = forwardRef<
	SwiperRef,
	GreatJoySwiperProps
>(
	(
		{
			items,
			height = 200,
			autoplay = true,
			interval = 3000,
			loop = true,
			lazyLoadThreshold = 200,
			placeholder,
			onSlideChange,
			renderCustomItem,
			className,
		},
		ref
	) => {
		const [_activeIndex, setActiveIndex] = useState<number>(0);
		const swiperRef = useRef<any>(null);

		// 处理轮播切换
		const handleChange = useCallback(
			(index: number) => {
				setActiveIndex(index);
				onSlideChange?.(index);
			},
			[onSlideChange]
		);

		// 渲染轮播项
		const renderSwiperItem = useCallback(
			(item: SwiperItemType, index: number) => {
				if (renderCustomItem) {
					return renderCustomItem(item, index);
				}

				return (
					<LazyLoadImage
						key={item.id}
						src={item.imageUrl}
						alt={item.alt}
						placeholder={placeholder}
						lazyLoadThreshold={lazyLoadThreshold}
					/>
				);
			},
			[renderCustomItem, placeholder, lazyLoadThreshold]
		);

		// 暴露方法给外界
		useImperativeHandle(ref, () => ({
			swipeTo: (index: number) => {
				swiperRef.current?.swipeTo(index);
			},
			swipeNext: () => {
				swiperRef.current?.swipeNext();
			},
			swipePrev: () => {
				swiperRef.current?.swipePrev();
			},
		}));

		return (
			<Swiper
				ref={swiperRef}
				className={`greatJoy-lazy-swiper ${className || ""}`}
				style={{ height }}
				autoplay={autoplay}
				autoplayInterval={interval}
				loop={loop}
				onIndexChange={handleChange}>
				{items?.map((item, index) => (
					<Swiper.Item key={item.id || index}>
						{renderSwiperItem(item, index)}
					</Swiper.Item>
				))}
			</Swiper>
		);
	}
);

export default GreatJoySwiper;